<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度翻译API测试</title>
    <script src="https://unpkg.com/crypto-js@4.1.1/crypto-js.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .success { border-color: #4CAF50; background: #f1f8e9; }
        .error { border-color: #f44336; background: #ffebee; }
        .warning { border-color: #ff9800; background: #fff3e0; }
        button {
            background: #2196F3;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #1976D2; }
        textarea {
            width: 100%;
            height: 100px;
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .log {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>百度翻译API测试</h1>
        
        <div class="test-section">
            <h3>API配置</h3>
            <p><strong>APP ID:</strong> 20250627002391301</p>
            <p><strong>APP Key:</strong> ZPM1rdKh_etnWFatwYR0</p>
            <p><strong>API URL:</strong> https://fanyi-api.baidu.com/api/trans/vip/translate</p>
        </div>

        <div class="test-section">
            <h3>翻译测试</h3>
            <input type="text" id="testText" value="你好，世界" placeholder="输入要翻译的文本">
            <br>
            <select id="targetLang">
                <option value="en">英语</option>
                <option value="pt">葡萄牙语</option>
            </select>
            <br>
            <button onclick="testTranslation()">测试翻译</button>
            <button onclick="testCORS()">测试CORS</button>
            <button onclick="testSignature()">测试签名</button>
            <button onclick="clearLog()">清除日志</button>
        </div>

        <div class="test-section">
            <h3>翻译结果</h3>
            <div id="result"></div>
        </div>

        <div class="test-section">
            <h3>调试日志</h3>
            <div id="log" class="log"></div>
        </div>
    </div>

    <script>
        const appId = '20250627002391301';
        const appKey = 'ZPM1rdKh_etnWFatwYR0';
        
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const time = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'warn' ? 'warning' : 'success';
            logDiv.innerHTML += `<div class="${className}">[${time}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
        
        function clearLog() {
            document.getElementById('log').innerHTML = '';
            document.getElementById('result').innerHTML = '';
        }
        
        // 测试签名生成
        function testSignature() {
            const query = '你好，世界';
            const salt = Date.now().toString();
            const from = 'zh';
            const to = 'en';
            
            // 按照百度文档的签名算法
            const signStr = appId + query + salt + appKey;
            const sign = CryptoJS.MD5(signStr).toString();
            
            log(`签名字符串: ${signStr}`, 'info');
            log(`MD5签名: ${sign}`, 'info');
            
            // 构建请求参数
            const params = {
                q: query,
                from: from,
                to: to,
                appid: appId,
                salt: salt,
                sign: sign
            };
            
            log(`请求参数: ${JSON.stringify(params, null, 2)}`, 'info');
        }
        
        // 测试CORS
        async function testCORS() {
            const testUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
            
            try {
                log('测试CORS访问...', 'info');
                const response = await fetch(testUrl, {
                    method: 'GET',
                    mode: 'cors'
                });
                log(`CORS测试成功，状态码: ${response.status}`, 'success');
            } catch (error) {
                log(`CORS测试失败: ${error.message}`, 'error');
                log('百度翻译API不支持浏览器直接调用（CORS限制）', 'error');
            }
        }
        
        // 测试翻译
        async function testTranslation() {
            const text = document.getElementById('testText').value;
            const targetLang = document.getElementById('targetLang').value;
            
            if (!text.trim()) {
                log('请输入要翻译的文本', 'warn');
                return;
            }
            
            const salt = Date.now().toString();
            const from = 'zh';
            const to = targetLang;
            
            // 生成签名
            const signStr = appId + text + salt + appKey;
            const sign = CryptoJS.MD5(signStr).toString();
            
            const params = new URLSearchParams({
                q: text,
                from: from,
                to: to,
                appid: appId,
                salt: salt,
                sign: sign
            });
            
            const url = `https://fanyi-api.baidu.com/api/trans/vip/translate?${params}`;
            
            log(`开始翻译: "${text}" (${from} -> ${to})`, 'info');
            log(`请求URL: ${url}`, 'info');
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                log(`HTTP状态码: ${response.status}`, response.ok ? 'success' : 'error');
                
                const data = await response.json();
                log(`API响应: ${JSON.stringify(data, null, 2)}`, 'info');
                
                if (data.trans_result && data.trans_result.length > 0) {
                    const result = data.trans_result[0].dst;
                    document.getElementById('result').innerHTML = `
                        <div class="success">
                            <strong>翻译成功:</strong><br>
                            原文: ${text}<br>
                            译文: ${result}
                        </div>
                    `;
                    log(`翻译成功: "${result}"`, 'success');
                } else if (data.error_code) {
                    const errorMsg = getErrorMessage(data.error_code);
                    document.getElementById('result').innerHTML = `
                        <div class="error">
                            <strong>翻译失败:</strong><br>
                            错误代码: ${data.error_code}<br>
                            错误信息: ${data.error_msg || errorMsg}
                        </div>
                    `;
                    log(`翻译失败: ${data.error_code} - ${errorMsg}`, 'error');
                } else {
                    log('未知的API响应格式', 'error');
                }
                
            } catch (error) {
                log(`请求失败: ${error.message}`, 'error');
                document.getElementById('result').innerHTML = `
                    <div class="error">
                        <strong>请求失败:</strong><br>
                        ${error.message}
                    </div>
                `;
                
                // 如果是CORS错误，提供解决方案
                if (error.message.includes('CORS') || error.message.includes('fetch')) {
                    log('解决方案：百度翻译API需要后端代理调用，不能直接从浏览器调用', 'warn');
                    log('建议：使用免费的Google翻译API或其他支持CORS的翻译服务', 'warn');
                }
            }
        }
        
        function getErrorMessage(errorCode) {
            const errorMessages = {
                '52001': '请求超时，请重试',
                '52002': '系统错误，请重试',
                '52003': '未授权用户',
                '54001': '签名错误',
                '54003': '访问频率受限',
                '54004': '账户余额不足',
                '54005': '长query请求频繁',
                '58000': '客户端IP非法',
                '58001': '译文语言方向不支持',
                '58002': '服务当前已关闭',
                '90107': '认证未通过或未生效'
            };
            return errorMessages[errorCode] || '未知错误';
        }
        
        // 页面加载时运行基本测试
        window.onload = function() {
            log('百度翻译API测试页面已加载', 'info');
            log('提示：百度翻译API通常不支持浏览器直接调用（CORS限制）', 'warn');
            testSignature();
        };
    </script>
</body>
</html> 